﻿using System.Security.Principal;
using System.Text;
using RpcExtend.Collect;
using RpcExtend.Model;
using RpcExtend.Service.Interface;
using RpcHelper;
using RpcModel;
using RpcModularModel.Identity.Model;
using RpcModularModel.Identity.Msg;

namespace RpcExtend.Service.Service
{
    internal class IdentityService : IIdentityService
    {
        private readonly IIdentityAppCollect _IdentityApp;
        private readonly IIdentityProwerCollect _IdentityPrower;
        public IdentityService(IIdentityAppCollect identityApp, IIdentityProwerCollect identityPrower)
        {
            this._IdentityApp = identityApp;
            this._IdentityPrower = identityPrower;
        }
        public void RefreshPrower(RefreshIdentityPrower refresh)
        {
            refresh.SystemType.ForEach(c =>
            {
                _IdentityPrower.Refresh(refresh.AppId, c);
            });
        }
        public void Refresh(RefreshIdentity identity)
        {
            _IdentityApp.Refresh(identity.AppId);
            if (!identity.IsEnable && identity.EventType != "delete")
            {
                new UpdateIdentity { AppId = identity.AppId }.Send();
            }
        }
        public IdentityDatum GetIdentity(Guid id, MsgSource source)
        {
            IdentityApp app = this._IdentityApp.GetApp(id);
            if (!app.IsEnable || (app.EffectiveDate.HasValue && app.EffectiveDate.Value < HeartbeatTimeHelper.CurrentDate))
            {
                return new IdentityDatum
                {
                    IsValid = false
                };
            }
            IdentityPrower[] prowers = this._IdentityPrower.GetPrower(id, source.SystemType);
            if (prowers.Length == 0)
            {
                return new IdentityDatum
                {
                    IsValid = false
                };
            }
            return new IdentityDatum
            {
                IsValid = true,
                AppName = app.AppName,
                Path = prowers.Convert(a => a.ResourceType == RpcModularModel.Resource.ResourceType.API接口, a => a.Value),
                Routes = prowers.Convert(a => a.ResourceType == RpcModularModel.Resource.ResourceType.RPC接口, a => a.Value),
            };
        }
    }
}
